package thread.localThread;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 模拟实现 ThreadLocal 类的原理
 * Created by 4790K_NSL on 2017/4/20.
 */
public class ThreadLoaclSelf {


    public static void main(String[] args) {
        ThreadLoaclSelf threadLoaclSelf=new ThreadLoaclSelf();
        threadLoaclSelf.demo();
    }

    public void demo(){
        final  Business business=new Business();
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Integer value=new Random().nextInt();
                    business.saveData(value);
                    System.out.println(Thread.currentThread().getName() + " save :" + value);
                    System.out.println("**********************");
                    System.out.println(Thread.currentThread().getName() + " lode :" + business.loadData());
                    System.out.println("**********************");

                }
            }).start();
        }
    }

    class Business {
        private MyThreadLocal mythreadLocal=new MyThreadLocal();

        public void saveData(Integer value){
            mythreadLocal.put(value);
        }

        public Integer loadData(){
            return mythreadLocal.get();
        }
    }

    class MyThreadLocal{
        private Map<Thread,Integer> threadMap=new HashMap<>();

        public void put(Integer integer){
            threadMap.put(Thread.currentThread(),integer);
        }

        public Integer get(){
            return threadMap.get(Thread.currentThread());
        }
    }
}
